# coding=utf-8
import urllib2

from server.base.beanret import BeanRet
from config import Config

'''
服务器请求客户端
'''


class Client:
    def __init__(self):
        # host = "http://192.168.1.96:5000"
        # type = "uav"
        # 服务器ip
        host = Config().read("Server", "host")
        self.host = str(host)
        type = Config().read("Server", "type")
        self.type = str(type)  # 类型 终端device,无人机uav
        clientId = Config().read("Server", "clientId")  # 设备id
        self.clientId = str(clientId)
        lon = Config().read("Server", "lon")  # 经度
        self.lon = str(lon)
        lat = Config().read("Server", "lat")  # 纬度
        self.lat = str(lat)
        angle = Config().read("Server", "angle")  # 角度
        self.angle = str(angle)
        port = Config().read("Server", "port")  # 客户端服务端口
        self.port = str(port)

    def reg(self):
        '''
        向服务器注册
        :return:
        '''
        url = self.host + "/reg/" + self.type + "/" + self.clientId + "/" + self.port + ".shtml"
        response = urllib2.urlopen(url)
        result = response.read()
        print(result)

    def log(self, msg):
        '''
        向服务器端发送日志
        :param msg:
        :return:
        '''
        url = self.host + "/" + self.clientId + "/msg.shtml"
        data = "msg=[终端 " + self.clientId + "]-" + msg
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        result = response.read()
        print(result)

    def getCmd(self):
        '''
        获得服务器的指令
        :return:
        '''
        url = self.host + "/" + self.clientId + "/get/cmd.shtml"
        response = urllib2.urlopen(url)
        result = response.read()
        beanret = BeanRet()
        beanret = beanret.toObj(result)
        return str(beanret.data)

    def sendData(self, text):
        """
        向服务器推送无人机实时数据
        :return:
        """
        url = self.host + "/client/sendData.shtml"
        text = text + " " + self.clientId
        data = str("text=" + text)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        result = response.read()
        print(result)

    def notify(self, text):
        """
        向服务器发送信息
        :param text:
        :return:
        """
        """
       向服务器推送异常信息或指令执行结果
       :return:
       """
        # url = self.host + "/client/notify"
        url = self.host + "/client/notify.shtml"
        text = text + "/" + self.clientId
        data = str("text=" + text)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        result = response.read()
        print(result)
